using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using JHS.EncryptionLibrary;

namespace Widgetsphere.WebUtils
{
	public class SecurityHelper
	{
		private const string DEFAULT_KEY = "qweasdzxc";

		public static string Encrypt(string plainText)
		{
			return Encrypt(plainText, DEFAULT_KEY);
		}

		public static string Encrypt(string plainText, string encryptionKey)
		{
			string encryptedString = string.Empty;
			if ((encryptionKey == null) || (encryptionKey == ""))
				encryptionKey = DEFAULT_KEY;

			//Prepare EncryptionEngine
			EncryptionEngine ee = new EncryptionEngine(EncryptionEngine.AlgorithmType.TripleDES);
			ee.Key = encryptionKey;

			// Encrypt string
			try
			{
				encryptedString = ee.Encrypt(plainText);
			}
			catch (Exception ex)
			{
				throw new InvalidOperationException("An error occured while encrypting the string " + encryptedString + ".", ex);
			}
			finally
			{
				ee.DestroyEngine();
			}

			return encryptedString;
		}

		public static string Decrypt(string encryptedString)
		{
			return Decrypt(encryptedString, DEFAULT_KEY);
		}

		public static string Decrypt(string encryptedString, string encryptionKey)
		{
			string decryptedString = string.Empty;

			if ((encryptionKey == null) || (encryptionKey == ""))
				encryptionKey = DEFAULT_KEY;

			//Prepare EncryptionEngine
			EncryptionEngine ee = new EncryptionEngine(EncryptionEngine.AlgorithmType.TripleDES);
			ee.Key = encryptionKey;

			//Decrypt string
			try
			{
				decryptedString = ee.Decrypt(encryptedString);
			}
			catch (Exception ex)
			{
				throw new InvalidOperationException("An error occured while decrypting the string " + encryptedString + ".", ex);
			}
			finally
			{
				//Clean up
				ee.DestroyEngine();
			}

			return decryptedString;

		}

	}
}
